package com.refuel.service;

import cn.hutool.core.util.ObjectUtil;
import com.refuel.convert.UserConvert;
import com.refuel.domain.User;
import com.refuel.entity.UserEntity;
import com.refuel.repository.UserRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author zhanghao
 * @description
 * @date 2024/5/24 10:42
 **/
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    /**
     * 保存用户信息
     *
     * @param user 用户信息
     */
    @Override
    public void save(User user) {

        UserEntity userEntity = UserConvert.toEntity(user);
        if (userEntity == null || userEntity.getUid()== null) {
            return;
        }

        UserEntity oldUserEntity = userRepository.findByUid(userEntity.getUid());
        if (ObjectUtil.isNotEmpty(oldUserEntity) && ObjectUtil.isNotNull(oldUserEntity.getId())) {
            userEntity.setId(oldUserEntity.getId());
        }
        userRepository.save(userEntity);
    }

    /**
     * 根据用户id查询用户信息
     * @param uid 用户id
     * @return 用户信息
     */
    @Override
    public User findUser(String uid) {
        UserEntity userEntity = userRepository.findByUid(uid);

        return UserConvert.toDomain(userEntity);
    }
}
